﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RMS.Common;
using RMS.DB;

namespace RMS
{
    public partial class frmSellLooseStone : IChangeFont
    {
        private int precisionFormat = Convert.ToInt32(ConfigurationManager.AppSettings["Precision"]);
        //
        private readonly LooseStoneMng _stoneMng = new LooseStoneMng();
        private readonly InvoicesMng invoicesMng = new InvoicesMng();
        private readonly SoldItemsMng soldItemsMng = new SoldItemsMng();
        private readonly CustomersMng customersMng = new CustomersMng();
        private readonly Invoice draftInvoice;
        private string[] _customerInfo = new string[5];
        private decimal _totalCost;
        private decimal _totalQty;
        private string draftOrderCode;
        private List<LooseStone> listCart;

        public frmSellLooseStone()
        {
            InitializeComponent();
            listCart = new List<LooseStone>();
        }
        public frmSellLooseStone(Invoice _draft)
        {
            InitializeComponent();
            listCart = new List<LooseStone>();
            draftInvoice = _draft;
        }

        private void txtTotalCost_Leave(object sender, EventArgs e)
        {
            try
            {
                var a = Convert.ToDecimal(txtTotalCost.Text.Trim());
            }
            catch(FormatException)
            {
                txtTotalCost.Text = "";
                return;
            }
            if (!string.IsNullOrEmpty(txtTotalCost.Text.Trim()))
            {
                txtTotalCost.Text = Utilities.FormatNumber(Convert.ToDecimal(txtTotalCost.Text.Trim()), precisionFormat);
            }
        }

        private void frmSellLooseStone_Load(object sender, EventArgs e)
        {
            
            BindAllInventory();
            gridCart.AutoGenerateColumns = false;
            btnSaveDraft.Enabled = false;            
            if (draftInvoice != null)
            {
                BindDraftData(draftInvoice);
                draftOrderCode = draftInvoice.OrderCode;
            }
            gridInventoryList.ClearSelection();
            txtCertNo.Focus();
        }
        private void BindDraftData(Invoice item)
        {
            List<SoldItems> listSoldItem = soldItemsMng.GetListItems(item.OrderCode);
            foreach (SoldItems soldItem in listSoldItem)
            {
                var itemStone = new LooseStone()
                {
                    CertNo = soldItem.ProductID,
                    Weight = soldItem.ExportWeight,
                    ImportPrice = soldItem.ImportPrice,
                    ExportPrice = soldItem.ExportPrice,
                    ExportQuantity = soldItem.ExportQuantity,
                    Quantity = soldItem.ImportQuantity,
                };
                listCart.Add(itemStone);
                _totalQty += Convert.ToInt32(soldItem.ExportQuantity);
                _totalCost += Convert.ToDecimal(soldItem.ExportPrice);
            }
            txtTotalProduct.Text = Convert.ToString(_totalQty);
            txtTotalPrice.Text = Utilities.FormatNumber(_totalCost, precisionFormat);
            if (listCart != null)
            {
                gridCart.DataSource = listCart;
            }
        }

        private void BindAllInventory()
        {
            List<LooseStone> src = _stoneMng.GetRemainInStock();
            gridInventoryList.AutoGenerateColumns = false;
            gridInventoryList.DataSource = src;            
        }

        private void gridInventoryList_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            foreach (DataGridViewRow row in gridInventoryList.Rows)
            {
                if (row.Selected)
                {
                    var item = _stoneMng.GetItemByElements(Convert.ToString(row.Cells[0].Value));
                    BindDataToTextbox(item);
                    //Set max value for quantity
                    txtQuantity.Maximum = Convert.ToDecimal(item.Quantity);
                }
            }
        }

        private void BindDataToTextbox(LooseStone item)
        {
            txtCertNo.Text = item.CertNo;
            txtCertType.Text = item.CertType;
            txtColor.Text = item.Color;
            txtImportPrice.Text = Utilities.FormatNumber(Convert.ToDecimal(item.ImportPrice), precisionFormat);
            txtLength.Text = Convert.ToString(item.Length);
            txtStoneType.Text = item.StoneType;
            txtweight.Text = Utilities.FormatNumber(Convert.ToDecimal(item.Weight), 3);
            txtWidth.Text = Convert.ToString(item.Width);
            txtCategory.Text = item.Category;
        }

        private void btnCustomerInfo_Click(object sender, EventArgs e)
        {
            var location = new frmInsertCustomerInfo(){ShowInTaskbar = false};
            if (location.ShowDialog() == DialogResult.OK)
            {
                string[] arr = location.result.Split('#'); // get customer info arr           
                _customerInfo = arr;
                txtCusName.Text = arr[1];
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            LooseStone item = _stoneMng.GetItemByElements(txtCertNo.Text.Trim());
            if (item == null)
            {
                MessageBox.Show(Constants.Msg.NotItemExist);
                ClearAllTextbox();
                return;
            }
            BindDataToTextbox(item);
            txtCertNo.Focus();
        }

        private void btnCart_Click(object sender, EventArgs e)
        {
            var item = _stoneMng.GetItemByElements(txtCertNo.Text.Trim());
            if (item == null)
            {
                MessageBox.Show(Constants.Msg.NotItemExist);
                return;
            }
            if (CheckRequiredField())
            {                

                if (listCart.Count != 0 && listCart.Any(inv => item.CertNo == inv.CertNo))
                {
                    MessageBox.Show(Constants.Msg.ExistedInCart, "Chú ý");
                    return;
                }

                item.ExportQuantity = Convert.ToInt32(txtQuantity.Text.Trim());
                item.ExportPrice = Convert.ToDecimal(txtTotalCost.Text.Trim());
                item.Weight = Convert.ToDecimal(txtweight.Text.Trim());
                listCart.Add(item);

                _totalCost += Convert.ToDecimal(item.ExportPrice);
                _totalQty += Convert.ToDecimal(item.ExportQuantity);
                txtTotalPrice.Text = Utilities.FormatNumber(_totalCost, precisionFormat);
                txtTotalProduct.Text = Convert.ToString(_totalQty);

                gridCart.DataSource = null;
                gridCart.DataSource = listCart;
                ClearAllTextbox();
                btnSaveDraft.Enabled = true;
            }
        }     

        private void ClearAllTextbox()
        {
            txtCertNo.Text = 
            txtCertType.Text = 
            txtColor.Text =
            txtImportPrice.Text = 
            txtLength.Text =
            txtStoneType.Text =
            txtweight.Text = 
            txtWidth.Text = 
            txtTotalCost.Text =             
            txtCategory.Text = "";
            txtQuantity.Text = "1";
            txtCertNo.Focus();
        }

        private bool CheckRequiredField()
        {
            if (string.IsNullOrEmpty(txtCertNo.Text.Trim()))
            {
                MessageBox.Show("Bạn hãy điền mã chứng chỉ của sản phẩm bán.", "Chú ý");
                txtCertNo.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(txtTotalCost.Text.Trim()))
            {
                MessageBox.Show("Bạn hãy điền giá sản phẩm bán.", "Chú ý");
                txtTotalCost.Focus();
                return false;
            }

            return true;
        }

        private void gridCart_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 4)
            {
                foreach (DataGridViewRow row in gridCart.Rows)
                {
                    if (row.Cells[4].Selected)
                    {
                        row.Selected = true;
                        RemoveCartItem();
                        txtTotalPrice.Text = Utilities.FormatNumber(_totalCost, precisionFormat);
                        txtTotalProduct.Text = Convert.ToString(_totalQty);
                        return;
                    }
                }
            }
        }

        private void RemoveCartItem()
        {
            int flag = gridCart.Rows.Cast<DataGridViewRow>().Count(row => Convert.ToBoolean(row.Selected));
            if (flag == 0)
            {
                MessageBox.Show(Constants.Msg.ChooseOneItem, "Chú ý");
                return;
            }

            if (MessageBox.Show(Constants.Msg.DropOutShopCart, "Chú ý", MessageBoxButtons.YesNo) != DialogResult.Yes)
                return;
            foreach (DataGridViewRow row in gridCart.Rows)
            {
                if (Convert.ToBoolean(row.Selected))
                {
                    _totalCost -= Convert.ToDecimal(row.Cells[2].Value);
                    _totalQty -= Convert.ToDecimal(row.Cells[1].Value);
                    listCart.RemoveAt(row.Index);
                }
            }

            gridCart.DataSource = null;
            gridCart.DataSource = listCart;
        }

        private void AddCustomerInfo(decimal totalbuyingCost)
        {
            if (_customerInfo != null && !string.IsNullOrEmpty(txtCusName.Text.Trim()))
            {
                Customer item = customersMng.GetItemByElements(_customerInfo[0]);
                if (item == null)
                    customersMng.AddItem(_customerInfo[0], _customerInfo[1], _customerInfo[2], _customerInfo[3],
                                         _customerInfo[4],totalbuyingCost);
                else
                {
                    customersMng.UpdateItem(_customerInfo[0], totalbuyingCost);
                }
            }                        
        }

        private void btnBigSell_Click(object sender, EventArgs e)
        {
            if (listCart.Count == 0)
            {
                MessageBox.Show(Constants.Msg.SellerrorAlert, "Chú ý");
                return;
            }
            if (string.IsNullOrEmpty(txtSaleInvoice.Text.Trim()))
            {
                MessageBox.Show(Constants.Msg.SaleInvoiceRequired, "Chú ý");
                txtSaleInvoice.Focus();
                return;
            }
            if (IsExistInvoiceNo(txtSaleInvoice.Text.Trim()))
            {
                MessageBox.Show(Constants.Msg.InvoiceNoExist, "Chú ý");
                return;
            }
            AddToSoldItems();
            
        }

        private void AddToSoldItems()
        {
            if (MessageBox.Show(Constants.Msg.ConfirmSale, "Chú ý", MessageBoxButtons.YesNo) == DialogResult.No) return;
            var orderCode = OrderCodeGenerating();
            decimal totalIm = 0;
            decimal totalEx = 0;
            foreach (var item in listCart)
            {
                var itemInStock = _stoneMng.GetItemByElements(item.CertNo);
                if (itemInStock!= null && itemInStock.Quantity == 0)
                {
                    MessageBox.Show("Số lượng sản phẩm [" + itemInStock.CertNo + "] không đủ hàng trong kho.\nĐơn hàng này sẽ không được thực hiện", "Chú ý");
                    draftOrderCode = "";
                    return;
                }
                _stoneMng.UpdateItem(item.CertNo);

                totalIm += Convert.ToDecimal(item.ImportPrice);
                totalEx += Convert.ToDecimal(item.ExportPrice);
                if (!string.IsNullOrEmpty(draftOrderCode))
                {
                    soldItemsMng.DeleteItem(item.CertNo, draftOrderCode);
                    soldItemsMng.AddNewSoldItems(item.CertNo, Constants.IsStoneItem, draftOrderCode,
                                  totalIm, 1,
                                  Convert.ToDecimal(item.ExportPrice), Convert.ToDecimal(item.Weight),
                                  DateTime.Now, _customerInfo[0], txtSaleInvoice.Text.Trim());        
                }
                else
                soldItemsMng.AddNewSoldItems(item.CertNo, Constants.IsStoneItem, orderCode,
                                  totalIm, 1,
                                  Convert.ToDecimal(item.ExportPrice), Convert.ToDecimal(item.Weight),
                                  DateTime.Now, _customerInfo[0], txtSaleInvoice.Text.Trim());              
            }
            AddCustomerInfo(totalEx);
            if (string.IsNullOrEmpty(draftOrderCode) && !invoicesMng.IsExist(draftOrderCode))
                invoicesMng.AddNewItems(_customerInfo[0],txtSaleInvoice.Text.Trim(), orderCode, totalIm, totalEx, DateTime.Now, Constants.IsStoneItem, false);
            else invoicesMng.UpdateItem(draftOrderCode, _customerInfo[0], txtSaleInvoice.Text.Trim(), totalIm, totalEx, DateTime.Now, false);
            MessageBox.Show(Constants.Msg.SaleSuccessful, "Chú ý");
            
            //Clear all
            BindAllInventory();
            gridCart.DataSource = null;

            _totalQty = 0;
            _totalCost = 0;
            listCart = new List<LooseStone>();
            _customerInfo = new string[5];
            btnSaveDraft.Enabled = false;
            txtTotalPrice.Text = txtTotalProduct.Text = txtCusName.Text = "";
            txtSaleInvoice.Text = "";
            ClearAllTextbox();
        }

        private void btnSaveDraft_Click(object sender, EventArgs e)
        {
            if (listCart.Count == 0) return;
            string orderCode = OrderCodeGenerating();
            decimal totalIm = 0;
            decimal totalEx = 0;
            var listProductId = "";
            foreach (LooseStone item in listCart)
            {
                //Add draft item to database
                if (!string.IsNullOrEmpty(draftOrderCode))
                {
                    soldItemsMng.DeleteItem(item.CertNo, draftOrderCode);
                    soldItemsMng.AddNewSoldItems(item.CertNo, Constants.IsStoneItem, draftOrderCode,
                                  Convert.ToDecimal(item.ImportPrice), Convert.ToInt32(item.Quantity),
                                  Convert.ToDecimal(item.ExportPrice), Convert.ToDecimal(item.Weight),
                                  DateTime.Now, "", "isdraft");
                }
                else      
                soldItemsMng.AddNewSoldItems(item.CertNo, Constants.IsStoneItem, orderCode,
                                  Convert.ToDecimal(item.ImportPrice), Convert.ToInt32(item.Quantity),
                                  Convert.ToDecimal(item.ExportPrice), Convert.ToDecimal(item.Weight),
                                  DateTime.Now, "", "isdraft");
              
                totalIm += Convert.ToDecimal(item.ImportPrice);
                totalEx += Convert.ToDecimal(item.ExportPrice);
                listProductId += ", " + item.CertNo;
            }
            
            // safe draft invoice and  list productId
            if (!string.IsNullOrEmpty(draftOrderCode))
            {
                invoicesMng.UpdateItem(draftOrderCode, "", listProductId.TrimStart(',', ' '), totalIm, totalEx, DateTime.Now, true);
            } else
            invoicesMng.AddNewItems("", listProductId.TrimStart(',', ' '), orderCode, totalIm, totalEx, DateTime.Now, Constants.IsStoneItem, true);
             //AddCustomerInfo(0);
            MessageBox.Show(Constants.Msg.SaveDraftSuccess, "Chú ý");
            ClearAllTextbox();

            _totalQty = 0;
            _totalCost = 0;
            listCart = new List<LooseStone>();
            gridCart.DataSource = null;
            btnSaveDraft.Enabled = false;

            draftOrderCode = "";
            txtTotalPrice.Text = txtTotalProduct.Text = txtCusName.Text = "";
            txtSaleInvoice.Text = "";
        }


        private bool IsExistInvoiceNo(string currentNo)
        {
            var currentInvoice = invoicesMng.GetItemBySaleInvoiceNo(currentNo);
            if (currentInvoice == null) return false;
            return true;
        }

        private static string OrderCodeGenerating() // dd-mo-yy-hh-mi-ss format
        {
            string code = "";
            string yy = DateTime.Now.Year.ToString().Substring(2, 2);
            string mo = DateTime.Now.Month.ToString("00");
            string dd = DateTime.Now.Day.ToString("00");
            string hh = DateTime.Now.Hour.ToString("00");
            string mi = DateTime.Now.Minute.ToString("00");
            string ss = DateTime.Now.Second.ToString("00");
            code = dd + mo + yy + hh + mi + ss;
            return code;
        }
        
        private void btnSell_Click(object sender, EventArgs e)
        {
            
                QuickSaleItem();
                BindAllInventory();            
        }
        private void QuickSaleItem()
        {
            string orderCode = OrderCodeGenerating();            

            var item = _stoneMng.GetItemByElements(txtCertNo.Text.Trim());
            if (item == null)
            {
                MessageBox.Show(Constants.Msg.NotItemExist,"Chú ý");
                return;
            }
            if (CheckRequiredField())
            {
                if (string.IsNullOrEmpty(txtSaleInvoice.Text.Trim()))
                {
                    MessageBox.Show(Constants.Msg.SaleInvoiceRequired, "Chú ý");
                    txtSaleInvoice.Focus();
                    return;
                }
                if (MessageBox.Show(Constants.Msg.ConfirmSale, "Chú ý", MessageBoxButtons.YesNo) == DialogResult.No) return;
                _stoneMng.UpdateItem(item.CertNo);

                if (invoicesMng.AddNewItems(_customerInfo[0], txtSaleInvoice.Text.Trim(), orderCode, Convert.ToDecimal(txtImportPrice.Text),
                                            Convert.ToDecimal(txtTotalCost.Text.Trim()), DateTime.Now,
                                            Constants.IsStoneItem, false))
                {
                    soldItemsMng.AddNewSoldItems(item.CertNo, Constants.IsStoneItem, orderCode,
                                  Convert.ToDecimal(txtImportPrice.Text), 1,
                                  Convert.ToDecimal(txtTotalCost.Text.Trim()), Convert.ToDecimal(txtweight.Text),
                                  DateTime.Now, _customerInfo[0], txtSaleInvoice.Text.Trim());
                    AddCustomerInfo(Convert.ToDecimal(txtTotalCost.Text.Trim()));
                    MessageBox.Show(Constants.Msg.SaleSuccessful, "Chú ý");
                    _customerInfo = new string[5];
                    txtCusName.Text = "";
                    txtSaleInvoice.Text = "";
                    ClearAllTextbox();
                }
            }
        }
        private void validateNumeric(KeyPressEventArgs e)
        {
            var key = e.KeyChar;
            if ((key >= 48) && (key <= 58) || (key == 46) || key == 8 || key == 9 || (key >= 37 && key <= 40) || key == 144 || key == ',')
            {
                e.Handled = false;
            }
            else e.Handled = true;
        }

        private void txtTotalCost_KeyPress(object sender, KeyPressEventArgs e)
        {
            validateNumeric(e);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(Constants.Msg.ConfirmClose, "Chú ý", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (!string.IsNullOrEmpty(draftOrderCode))
                {
                    frmListDraftInvoices frm = new frmListDraftInvoices() { MdiParent = frmMain.ActiveForm, WindowState = FormWindowState.Maximized };
                    frm.Show();
                }
                Close();
            }
        }

        private void frmSellLooseStone_FormClosing(object sender, FormClosingEventArgs e)
        {
            //if (MessageBox.Show(Constants.Msg.ConfirmClose, "Chú ý", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            //{
            //    e.Cancel = true;
            //}
        }


    }
}
